package club.itstudio.IContainer.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
public class RecaptchaService {

    private final static String SecretKey = "6LffnfQaAAAAANRwLedoc-oQ3R9VxtM7lCpy2ejZ";
    private final static String VerifyURL = "https://recaptcha.net/recaptcha/api/siteverify";

    public boolean valid(String token) {
        if (token == null || token.isEmpty()) return false;

        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("secret", SecretKey);
        body.add("response", token);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request =
                new HttpEntity<>(body, headers);
        String response = restTemplate.postForObject(VerifyURL, request, String.class);

        ObjectMapper mapper = new ObjectMapper();
        Map resultMap;
        try {
            resultMap = mapper.readValue(response, Map.class);
        } catch (JsonProcessingException e) {
            return false;
        }
        Boolean success = (Boolean) resultMap.get("success");

        return success;
    }
}
